package org.zhxy.common.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.zhxy.common.response.ProfileResult;
import org.zhxy.core.system.service.PermissionService;
import org.zhxy.core.system.service.UserService;
import org.zhxy.entity.system.Permission;
import org.zhxy.entity.system.User;

import java.util.List;
import java.util.Set;

public class AutomaticRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;


    public void setName(String name) {
        super.setName("automaticRealm");
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ProfileResult result = (ProfileResult)principalCollection.getPrimaryPrincipal();
        Set<String> apisPerms = (Set<String>)result.getRoles().get("apis");
        SimpleAuthorizationInfo info = new  SimpleAuthorizationInfo();
        info.setStringPermissions(apisPerms);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password = new String( upToken.getPassword());
        User user = userService.findByUsername(username);
        if(user != null && user.getPassword().equals(password)) {
            if("2".equals(user.getStatus())){
                return null;
            }
            ProfileResult result = null;
            if("user".equals(user.getLevel())){
                List<Permission> permissions = permissionService.getPermissionListByUserId(user.getId());
                result = new ProfileResult(user,permissions);
            }else if("saasAdmin".equals(user.getLevel())){
                List<Permission> list = permissionService.findAll();
                result = new ProfileResult(user,list);
            }
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(result,user.getPassword(),this.getName());
            return info;
        }
        return null;
    }
}
